package linkedin;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Tzachi on 27/10/2014.
 * <p>
 * This class will be given a list of words (such as might be tokenized
 * from a paragraph of text), and will provide a method that takes two
 * words and returns the shortest distance (in words) between those two
 * words in the provided text.
 * Example:
 * WordDistanceFinder finder = new WordDistanceFinder(Arrays.asList("the", "quick", "brown", "fox", "quick"));
 * assert(finder.distance("fox","the") == 3);
 * assert(finder.distance("quick", "fox") == 1);
 */
public class WordDistanceFinder {

    public static int distance(List<String> words, String strA, String strB) {
        int distance = Integer.MAX_VALUE;
        int indexA = 0;
        int indexB = 0;
        boolean foundB = false;
        for (; indexA < words.size(); indexA++) {
            if (!words.get(indexA).equals(strA)) {
                continue;
            }
            while (indexB < indexA || !foundB) {
                if (words.get(indexB).equals(strB)){
                    distance = Math.min(distance, Math.abs(indexA - indexB));
                    foundB = true;
                }
                indexB++;
            }
            foundB = false;
        }
        while (indexB < words.size()){
            if (words.get(indexB).equals(strB)){
                distance = Math.min(distance, Math.abs(indexA - indexB));
            }
            indexB++;
        }
        return distance;
    }

    public static void main(String[] args) {
        List<String> words = Arrays.asList("the", "quick", "brown", "fox", "quick");
//        System.out.println(distance(words, "fox", "the"));
//        System.out.println(distance(words, "the", "fox"));
        System.out.println(distance(words, "quick", "fox"));
//        System.out.println(distance(words, "fox", "quick"));
//        System.out.println(distance(words, "fox", "bla"));
    }
}